<template>
  <div class="ai-conversation-container">
    <h1 class="page-title">AI会话记录</h1>
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>
    <div v-else-if="error" class="error-container">
      <el-alert
        :title="error"
        type="error"
        show-icon
      />
    </div>
    <div v-else class="conversation-content">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="conversation-sidebar">
            <div class="search-box">
              <el-input
                v-model="searchQuery"
                placeholder="搜索对话"
                prefix-icon="Search"
                clearable
                @input="filterConversations"
              />
            </div>
            
            <div class="conversation-list">
              <div
                v-for="(conv, index) in filteredConversations"
                :key="conv.id"
                :class="['conversation-item', { active: currentConversation && currentConversation.id === conv.id }]"
                @click="selectConversation(conv)"
              >
                <div class="conversation-title">{{ conv.title }}</div>
                <div class="conversation-meta">
                  <span class="date">{{ formatDate(conv.date) }}</span>
                  <span class="message-count">{{ conv.messages.length }}条消息</span>
                </div>
                <div class="conversation-preview">{{ getPreviewText(conv) }}</div>
              </div>
            </div>
          </div>
        </el-col>
        
        <el-col :span="18">
          <div class="conversation-main" v-if="currentConversation">
            <div class="conversation-header">
              <h2>{{ currentConversation.title }}</h2>
              <div class="conversation-actions">
                <el-button type="primary" plain size="small" @click="exportConversation">
                  导出对话
                </el-button>
                <el-button type="danger" plain size="small" @click="deleteConversation">
                  删除对话
                </el-button>
              </div>
            </div>
            
            <div class="conversation-info">
              <div class="info-item">
                <span class="label">关联任务：</span>
                <router-link :to="`/tasks/${taskId}`" class="task-link">
                  {{ currentConversation.taskTitle }}
                </router-link>
              </div>
              <div class="info-item">
                <span class="label">创建时间：</span>
                <span>{{ formatDateTime(currentConversation.date) }}</span>
              </div>
              <div class="info-item">
                <span class="label">提示模型：</span>
                <el-tag size="small">{{ currentConversation.model }}</el-tag>
              </div>
              <div class="info-item">
                <span class="label">会话目的：</span>
                <span>{{ currentConversation.purpose }}</span>
              </div>
            </div>
            
            <div class="messages-container" ref="messagesContainer">
              <div
                v-for="(message, index) in currentConversation.messages"
                :key="index"
                :class="['message', message.role === 'user' ? 'user-message' : 'ai-message']"
              >
                <div class="message-header">
                  <span class="message-role">{{ message.role === 'user' ? '用户' : 'AI助手' }}</span>
                  <span class="message-time">{{ formatTime(message.timestamp) }}</span>
                </div>
                <div class="message-content" v-html="formatMessage(message.content)"></div>
              </div>
            </div>
            
            <div class="conversation-summary" v-if="currentConversation.summary">
              <h3>对话摘要</h3>
              <div class="summary-content">{{ currentConversation.summary }}</div>
            </div>
            
            <div class="conversation-insights" v-if="currentConversation.insights && currentConversation.insights.length > 0">
              <h3>关键洞察</h3>
              <el-tag
                v-for="(insight, index) in currentConversation.insights"
                :key="index"
                class="insight-tag"
                effect="plain"
              >
                {{ insight }}
              </el-tag>
            </div>
            
            <div class="conversation-references" v-if="currentConversation.references && currentConversation.references.length > 0">
              <h3>参考资料</h3>
              <el-collapse>
                <el-collapse-item
                  v-for="(reference, index) in currentConversation.references"
                  :key="index"
                  :title="reference.title"
                  :name="index"
                >
                  <div class="reference-content">
                    <p>{{ reference.description }}</p>
                    <div class="reference-link">
                      <a :href="reference.url" target="_blank">查看资料</a>
                    </div>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </div>
          </div>
          
          <div class="empty-state" v-else>
            <el-empty description="请选择一个对话" />
          </div>
        </el-col>
      </el-row>
    </div>
    
    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认删除"
      width="30%"
    >
      <p>确定要删除对话 "{{ currentConversation ? currentConversation.title : '' }}" 吗？此操作不可恢复。</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确认删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { marked } from 'marked'

export default {
  name: 'AIConversation',
  components: {
    Search
  },
  setup() {
    const route = useRoute()
    const taskId = route.params.id
    const conversations = ref([])
    const currentConversation = ref(null)
    const loading = ref(true)
    const error = ref(null)
    const searchQuery = ref('')
    const messagesContainer = ref(null)
    const deleteDialogVisible = ref(false)
    
    const fetchConversations = async () => {
      try {
        loading.value = true
        // 这里替换为实际的 API 调用
        // const response = await fetch(`/api/tasks/${taskId}/ai-conversations`)
        // conversations.value = await response.json()
        
        // 模拟数据
        setTimeout(() => {
          conversations.value = [
            {
              id: 'conv-1',
              title: '需求分析讨论',
              taskTitle: '前端UI开发',
              date: '2024-05-10T14:30:00',
              model: 'GPT-4',
              purpose: '讨论UI组件需求和设计方案',
              messages: [
                {
                  role: 'user',
                  content: '我们需要设计一个任务进度跟踪组件，需要显示总体进度、里程碑和子任务的状态，你有什么建议？',
                  timestamp: '2024-05-10T14:30:15'
                },
                {
                  role: 'assistant',
                  content: "对于任务进度跟踪组件，我建议包含以下元素：\n\n1. **总体进度条**：直观显示任务完成百分比\n2. **里程碑时间轴**：显示关键节点状态和时间\n3. **子任务列表**：包含状态标签和单独进度条\n4. **筛选和排序功能**：方便查看不同状态任务\n\n可以使用Element Plus的Progress、Timeline和Table组件实现，结合响应式设计适应不同设备。",
                  timestamp: '2024-05-10T14:32:20'
                },
                {
                  role: 'user',
                  content: '里程碑时间轴如何设计才能更直观地展示当前所处阶段？',
                  timestamp: '2024-05-10T14:33:45'
                },
                {
                  role: 'assistant',
                  content: "里程碑时间轴的直观设计可以考虑：\n\n1. **颜色编码**：已完成(绿色)、进行中(蓝色)、未开始(灰色)、延期(黄色)、风险(红色)\n\n2. **节点样式**：\n   - 已完成：实心圆+对勾\n   - 当前：高亮边框+动效\n   - 未来：浅色边框\n\n3. **连接线**：显示阶段之间的关系\n\n4. **时间标记**：显示计划日期和实际日期的对比\n\n5. **悬停信息**：鼠标悬停显示详细信息\n\n6. **缩略视图**：在复杂项目中提供整体视图",
                  timestamp: '2024-05-10T14:36:10'
                }
              ],
              summary: '讨论了任务进度追踪组件的设计方案，包括总体进度条、里程碑时间轴和子任务列表的设计，特别强调了里程碑时间轴的直观展示方式。',
              insights: [
                '使用颜色编码区分不同状态',
                '里程碑节点应有明显的状态区分',
                '结合Element Plus组件库实现'
              ],
              references: [
                {
                  title: 'Element Plus Timeline组件',
                  description: 'Element Plus提供的时间轴组件，可用于实现里程碑展示',
                  url: 'https://element-plus.org/zh-CN/component/timeline.html'
                },
                {
                  title: 'Progress进度条组件',
                  description: '用于显示进度的组件，支持多种样式和状态',
                  url: 'https://element-plus.org/zh-CN/component/progress.html'
                }
              ]
            },
            {
              id: 'conv-2',
              title: '性能优化咨询',
              taskTitle: '前端UI开发',
              date: '2024-05-12T10:15:00',
              model: 'GPT-4',
              purpose: '讨论组件渲染性能优化方案',
              messages: [
                {
                  role: 'user',
                  content: '我们的任务列表在数据量大时渲染性能较差，有什么优化建议？',
                  timestamp: '2024-05-12T10:15:20'
                },
                {
                  role: 'assistant',
                  content: "针对大数据量任务列表的性能优化，建议：\n\n1. **虚拟滚动**：只渲染可视区域的元素，使用vue-virtual-scroller或Element Plus的虚拟列表\n\n2. **数据分页**：服务器端分页并只加载当前页数据\n\n3. **懒加载**：滚动到底部时加载更多数据\n\n4. **列表项组件优化**：\n   - 使用v-once对静态内容\n   - 为列表项设置适当的key\n   - 避免深层组件嵌套\n\n5. **避免不必要的计算属性重计算**\n\n6. **使用骨架屏替代加载动画**",
                  timestamp: '2024-05-12T10:18:40'
                },
                {
                  role: 'user',
                  content: '虚拟滚动和普通分页哪个更适合我们的场景？用户需要经常搜索和筛选任务列表。',
                  timestamp: '2024-05-12T10:21:15'
                },
                {
                  role: 'assistant',
                  content: "对于需要频繁搜索和筛选的任务列表，**服务器端分页**通常比虚拟滚动更适合，原因如下：\n\n**服务器端分页的优势**：\n1. 支持高效的服务器端搜索和筛选\n2. 数据库级别的排序和过滤更高效\n3. 减少前端数据处理压力\n4. 用户熟悉的交互模式\n5. 更容易实现复杂的表格功能(如列排序)\n\n**虚拟滚动的劣势**：\n1. 在频繁筛选场景下，需要加载所有数据才能前端筛选\n2. 搜索结果的跳转可能导致滚动位置管理复杂\n3. 与某些表格功能兼容性较差\n\n**建议方案**：\n实现服务器端分页、排序和筛选，每页加载适量数据(如20-50条)，配合骨架屏优化加载体验。",
                  timestamp: '2024-05-12T10:24:30'
                }
              ],
              summary: '讨论了大数据量任务列表的性能优化方案，包括虚拟滚动、服务器分页、懒加载等策略。针对需要频繁搜索和筛选的场景，建议使用服务器端分页和筛选。',
              insights: [
                '服务器端分页适合需要频繁搜索筛选的场景',
                '合理设置每页数据量(20-50条)可提升性能',
                '前端避免不必要的重渲染和计算'
              ],
              references: [
                {
                  title: 'Vue虚拟滚动性能优化',
                  description: '介绍Vue中虚拟滚动的实现和优化方法',
                  url: 'https://vuejs.org/guide/best-practices/performance.html'
                }
              ]
            }
          ]
          
          if (conversations.value.length > 0) {
            currentConversation.value = conversations.value[0]
          }
          
          loading.value = false
        }, 1000)
      } catch (err) {
        error.value = '获取AI会话数据失败'
        loading.value = false
        console.error(err)
      }
    }
    
    const filteredConversations = computed(() => {
      if (!searchQuery.value) {
        return conversations.value
      }
      
      const query = searchQuery.value.toLowerCase()
      return conversations.value.filter(conv => {
        return (
          conv.title.toLowerCase().includes(query) ||
          conv.purpose.toLowerCase().includes(query) ||
          conv.summary?.toLowerCase().includes(query) ||
          conv.messages.some(msg => msg.content.toLowerCase().includes(query))
        )
      })
    })
    
    const selectConversation = async (conversation) => {
      currentConversation.value = conversation
      
      // 等待DOM更新后滚动到消息底部
      await nextTick()
      if (messagesContainer.value) {
        messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
      }
    }
    
    const filterConversations = () => {
      // 如果当前没有对话被选中或当前选中的对话不在筛选结果中，
      // 则选择第一个筛选结果（如果有）
      if (
        !currentConversation.value ||
        !filteredConversations.value.some(conv => conv.id === currentConversation.value.id)
      ) {
        if (filteredConversations.value.length > 0) {
          selectConversation(filteredConversations.value[0])
        } else {
          currentConversation.value = null
        }
      }
    }
    
    const formatDate = (dateString) => {
      if (!dateString) return '-'
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN')
    }
    
    const formatTime = (dateTimeString) => {
      if (!dateTimeString) return '-'
      const date = new Date(dateTimeString)
      return date.toLocaleTimeString('zh-CN')
    }
    
    const formatDateTime = (dateTimeString) => {
      if (!dateTimeString) return '-'
      const date = new Date(dateTimeString)
      return date.toLocaleString('zh-CN')
    }
    
    const formatMessage = (content) => {
      // 使用Marked将Markdown格式转换为HTML
      return marked(content)
    }
    
    const getPreviewText = (conversation) => {
      if (conversation.messages.length === 0) {
        return '没有消息'
      }
      
      // 获取最后一条消息的内容，去除Markdown标记，并截取前30个字符
      const lastMessage = conversation.messages[conversation.messages.length - 1]
      const plainText = lastMessage.content.replace(/\*\*|__|\*|_|`|#|>|---|---|!/g, '')
      return plainText.length > 30 ? plainText.substring(0, 30) + '...' : plainText
    }
    
    const exportConversation = () => {
      if (!currentConversation.value) return
      
      // 构建导出文本
      let exportText = `# ${currentConversation.value.title}\n\n`
      exportText += `日期: ${formatDateTime(currentConversation.value.date)}\n`
      exportText += `任务: ${currentConversation.value.taskTitle}\n`
      exportText += `目的: ${currentConversation.value.purpose}\n\n`
      
      exportText += `## 对话内容\n\n`
      currentConversation.value.messages.forEach(msg => {
        const role = msg.role === 'user' ? '用户' : 'AI助手'
        exportText += `### ${role} (${formatDateTime(msg.timestamp)})\n\n`
        exportText += `${msg.content}\n\n`
      })
      
      if (currentConversation.value.summary) {
        exportText += `## 对话摘要\n\n${currentConversation.value.summary}\n\n`
      }
      
      if (currentConversation.value.insights && currentConversation.value.insights.length > 0) {
        exportText += `## 关键洞察\n\n`
        currentConversation.value.insights.forEach(insight => {
          exportText += `- ${insight}\n`
        })
        exportText += '\n'
      }
      
      if (currentConversation.value.references && currentConversation.value.references.length > 0) {
        exportText += `## 参考资料\n\n`
        currentConversation.value.references.forEach(ref => {
          exportText += `- [${ref.title}](${ref.url}): ${ref.description}\n`
        })
      }
      
      // 创建Blob和下载链接
      const blob = new Blob([exportText], { type: 'text/markdown' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `${currentConversation.value.title.replace(/\s+/g, '_')}_对话记录.md`
      a.click()
      URL.revokeObjectURL(url)
      
      ElMessage.success('对话已导出')
    }
    
    const deleteConversation = () => {
      if (!currentConversation.value) return
      deleteDialogVisible.value = true
    }
    
    const confirmDelete = () => {
      // 实际应用中应调用API删除对话
      const index = conversations.value.findIndex(conv => conv.id === currentConversation.value.id)
      if (index !== -1) {
        const deletedTitle = currentConversation.value.title
        conversations.value.splice(index, 1)
        
        // 选择新的当前对话
        if (conversations.value.length > 0) {
          currentConversation.value = conversations.value[0]
        } else {
          currentConversation.value = null
        }
        
        ElMessage.success(`对话"${deletedTitle}"已删除`)
      }
      
      deleteDialogVisible.value = false
    }
    
    onMounted(() => {
      fetchConversations()
    })
    
    return {
      taskId,
      conversations,
      currentConversation,
      loading,
      error,
      searchQuery,
      filteredConversations,
      messagesContainer,
      deleteDialogVisible,
      selectConversation,
      formatDate,
      formatTime,
      formatDateTime,
      formatMessage,
      getPreviewText,
      filterConversations,
      exportConversation,
      deleteConversation,
      confirmDelete
    }
  }
}
</script>

<style scoped>
.ai-conversation-container {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 24px;
}

.conversation-sidebar {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 15px;
  height: calc(100vh - 140px);
  display: flex;
  flex-direction: column;
}

.search-box {
  margin-bottom: 15px;
}

.conversation-list {
  flex: 1;
  overflow-y: auto;
}

.conversation-item {
  padding: 12px;
  border-radius: 4px;
  cursor: pointer;
  margin-bottom: 10px;
  border: 1px solid #e4e7ed;
  background-color: #fff;
  transition: all 0.3s;
}

.conversation-item:hover {
  background-color: #f0f5ff;
}

.conversation-item.active {
  background-color: #ecf5ff;
  border-color: #c6e2ff;
}

.conversation-title {
  font-weight: bold;
  margin-bottom: 5px;
  font-size: 15px;
}

.conversation-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
  margin-bottom: 5px;
}

.conversation-preview {
  font-size: 13px;
  color: #606266;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.conversation-main {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  height: calc(100vh - 140px);
  display: flex;
  flex-direction: column;
}

.conversation-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.conversation-header h2 {
  margin: 0;
  font-size: 18px;
}

.conversation-actions {
  display: flex;
  gap: 10px;
}

.conversation-info {
  display: flex;
  flex-wrap: wrap;
  background-color: #f5f7fa;
  padding: 10px 15px;
  border-radius: 4px;
  margin-bottom: 15px;
}

.info-item {
  margin-right: 20px;
  margin-bottom: 5px;
}

.info-item .label {
  font-weight: bold;
  color: #606266;
}

.task-link {
  color: #409eff;
  text-decoration: none;
}

.task-link:hover {
  text-decoration: underline;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 10px 0;
  margin-bottom: 15px;
}

.message {
  margin-bottom: 15px;
  padding: 12px 15px;
  border-radius: 6px;
  max-width: 80%;
}

.user-message {
  background-color: #ecf5ff;
  margin-left: auto;
}

.ai-message {
  background-color: #f4f4f5;
  margin-right: auto;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 13px;
}

.message-role {
  font-weight: bold;
}

.message-time {
  color: #909399;
}

.message-content {
  line-height: 1.6;
  font-size: 14px;
}

.message-content :deep(p) {
  margin: 0 0 10px;
}

.message-content :deep(ul),
.message-content :deep(ol) {
  padding-left: 20px;
  margin: 10px 0;
}

.message-content :deep(code) {
  background-color: rgba(0, 0, 0, 0.05);
  padding: 2px 4px;
  border-radius: 3px;
  font-family: 'Courier New', monospace;
}

.message-content :deep(pre) {
  background-color: #f8f8f8;
  padding: 10px;
  border-radius: 4px;
  overflow-x: auto;
  margin: 10px 0;
}

.conversation-summary,
.conversation-insights,
.conversation-references {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #e4e7ed;
}

.conversation-summary h3,
.conversation-insights h3,
.conversation-references h3 {
  font-size: 16px;
  margin-bottom: 10px;
}

.summary-content {
  color: #606266;
  line-height: 1.5;
  font-size: 14px;
}

.insight-tag {
  margin-right: 10px;
  margin-bottom: 8px;
}

.reference-content {
  padding: 5px 0;
  font-size: 14px;
}

.reference-link {
  margin-top: 5px;
}

.empty-state {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.loading-container,
.error-container {
  margin: 30px 0;
}
</style> 